// app.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const bcrypt = require('bcryptjs');
const multer = require('multer');
const User = require('./models/user');
const Match = require('./models/match');
const Project = require('./models/project');
const Team = require('./models/projectteam');
const Staff = require('./models/staff');
const Province = require('./models/province');
const City = require('./models/city');
const Home = require('./models/home');
const jwt = require('jsonwebtoken');
const authenticateToken = require('./authMiddleware');
const { Sequelize } = require('./models/database')

const ms = require('ms');
const { callbackify } = require('util');
const { error, log } = require('console');
const MatchGroup = require('./models/matchgroup');
const { match } = require('assert');
const TeamGroup = require('./models/teamgroup');
const ProjectTeam = require('./models/projectteam');
const TeamStaff = require('./models/teamstaff');

const app = express();
app.use((req, res, next) => {
    // 设置是否运行客户端设置 withCredentials
    // 即在不同域名下发出的请求也可以携带 cookie
    res.header("Access-Control-Allow-Credentials", true)
    // 第二个参数表示允许跨域的域名，* 代表所有域名  
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS') // 允许的 http 请求的方法
    // // 允许前台获得的除 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 这几张基本响应头之外的响应头
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')

    next()
})
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static('/static'))

const PORT = process.env.PORT || 3002;
// =====图片上传功能======

// 配置multer的存储设置

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 上传文件的存储路径
        cb(null, 'static/upload');
    },
    filename: function (req, file, cb) {
        // 上传文件的文件名
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    },
});
const upload = multer({ storage: storage });

app.post('/competition/upload', upload.single('file'), authenticateToken, async (req, res) => {

    if (req.file) {
        const path = `/static/upload/${req.file.filename}`;
        res.status(200).json({ success: true, msg: '上传文件成功', path: path });
    } else {
        res.status(500).json({ success: false, msg: '上传文件失败', error: '无法上传文件' });
    }
});



//==========比赛管理==========
// 0 选择一个比赛
app.get('/competition/match/:matchId', async (req, res) => {
    try {
        const match = await Match.findByPk(req.params.matchId)
        res.status(200).json({ success: true, msg: '选择比赛成功', match });
    } catch (error) {
        res.status(500).json({ success: false, msg: 'Error 选择比赛失败', error: error.message });
    }
})
// 0.1 获取所有可用的比赛
app.get('/competition/match', async (req, res) => {
    try {
        const matches = await Match.findAll({
            where: {
                disabled: 0
            }
        })
        res.status(200).json({ success: true, msg: '获取课用比赛成功', matches });
    } catch (error) {
        res.status(500).json({ success: false, msg: 'Error 选择比赛失败', error: error.message });
    }
});

// 0.2 获取所有的比赛,只允许管理员访问
app.get('/competition/showAllMatchByAdmin', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            const matches = await Match.findAll()
            res.status(200).json({ success: true, msg: '管理员获取所有比赛成功', matches });
        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }
    } catch (error) {
        res.status(500).json({ success: false, msg: 'Error 选择比赛失败', error: error.message });
    }
});
// 0.3 管理员删除比赛
app.delete('/competition/match/:matchId', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            const numDeleted = await Match.destroy({
                where: {
                    id: req.params.matchId
                }
            })
            res.status(200).json({ success: true, msg: '管理员删除比赛成功' });
        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }
    } catch (error) {
        res.status(500).json({ success: false, msg: 'Error 选择比赛失败', error: error.message });
    }
});
// 0.5 管理员修改比赛
app.put('/competition/match', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            const { id, title, deadline, telephone, mem, disabled } = req.body
            console.log(id, title, deadline, telephone, mem, disabled)
            const match = await Match.findByPk(id)
            console.log(match.id)
            match.title = title
            match.deadline = deadline
            match.telephone = telephone
            match.mem = mem
            match.disabled = disabled
            console.log(JSON.stringify(match))
            match.save()
            res.status(200).json({ success: true, msg: '管理员修改比赛成功', match });
        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }
    } catch (error) {
        res.status(500).json({ success: false, msg: 'Error 修改比赛失败', error: error.message });
    }
});
// 0.6 管理员添加赛事
app.post('/competition/match/add', authenticateToken, async (req, res) => {
    try {

        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目

            const match = await Match.create(req.body)
            if (!match) {
                return res.status(501).json({ success: false, msg: '无法添加比赛' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', match })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '不允许添加重名赛事，请换一个名字', error: error.message })
    }
})

//==========用户管理==========
//1 用户注册
app.post('/competition/user/reguser', async (req, res) => {
    try {
        const user = await User.create(req.body);
        res.status(200).json({ success: true, msg: '注册成功', user });
    } catch (error) {
        res.status(500).json({ success: false, msg: 'Error registering user', error: error.message });
    }
});

//2 用户登录
app.post('/competition/user/login', async (req, res) => {
    try {
        const { username, password, matchId } = req.body;
        const user = await User.findOne({ where: { username } });
        if (!user || !(await bcrypt.compare(password, user.password))) {
            return res.status(401).json({ success: false, msg: '账号或密码错误,请重新输入' });
        }
        const token = jwt.sign({ userId: user.id, role: user.role, matchId: matchId }, '123456', { expiresIn: '1h' });
        res.json({ success: true, message: '登录成功', token, data: user });
    } catch (error) {
        res.status(500).json({ success: false, msg: '服务器内部错误', error: error.message });
    }
});

//3. 修改密码
app.post('/competition/user/update/password', authenticateToken, async (req, res) => {
    try {
        const { username, password, newpassword } = req.body;
        console.log(req.body)
        let user = await User.findOne({ where: { username } })
        console.log(user)
        if (!user || ! await bcrypt.compare(password, user.password)) {
            return res.status(401).json({ success: false, msg: '原有用户名、密码不正确' })
        }
        user.password = newpassword
        let newuser = await user.save()
        res.status(200).json({ success: true, message: '修改密码成功', user: newuser });
    } catch (error) {
        res.status(500).json({ success: false, msg: '服务器内部错误', error: error.message });
    }

});


//==========赛项管理==========

//5. 添加赛项:project
app.post('/competition/project/add', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            let project = await Project.create(req.body)
            project.matchId = req.user.matchId
            if (!project) {
                return res.status(501).json({ success: false, msg: '无法添加项目' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', project })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }

    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：{"projectid":1,"projectname":"项目2","classificationId":1}', error: error.message })
    }
});
//5.1 查询赛项:project，所有赛事
app.get('/competition/project', authenticateToken, async (req, res) => {
    try {
        console.log(req.user)
        let projects = await Project.findAll({ where: { matchId: req.user.matchId } })
        return res.status(200).json({ success: true, msg: '成功', projects })
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：{"projectid":1,"projectname":"项目2","classificationId":1}', error: error.message })
    }
});

//5.2 删除赛项:project
app.delete('/competition/project/:projectId', authenticateToken, async (req, res) => {
    try {
        console.log(req.user)
        if (req.user.role == '管理员') {
            let num = await Project.destroy({ where: { id: req.params.projectId, matchId: req.user.matchId } })
            return res.status(200).json({ success: true, msg: '成功' })
        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：/competition/project/1', error: error.message })
    }
});

//5.3 修改赛项:project
app.put('/competition/project', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            const {
                id,
                projectName,
                projectPersonCount
            } = req.body
            let project = await Project.findByPk(id)
            project.projectName = projectName
            project.projectPersonCount = projectPersonCount
            project.save()
            if (!project) {
                return res.status(501).json({ success: false, msg: '无法修改项目' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', project })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }

    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：{"projectid":1,"projectname":"项目2","classificationId":1}', error: error.message })
    }
});
//5.4 查询某一赛项:project
app.get('/competition/project/:id', authenticateToken, async (req, res) => {
    try {
        console.log(req.user)
        let project = await Project.findOne({ where: { matchId: req.user.matchId, id: req.params.id } })
        return res.status(200).json({ success: true, msg: '成功', project })
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：/competition/project/:id', error: error.message })
    }
});

//==========赛事组别管理==========
//6. 添加赛事组别:matchgroup
app.post('/competition/matchgroup/add', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            const { groupname, minBirthDay, maxBirthDay } = req.body

            let matchgroup = MatchGroup.build({ groupname, minBirthDay, maxBirthDay, matchId: req.user.matchId })
            matchgroup = await matchgroup.save()
            if (!matchgroup) {
                return res.status(501).json({ success: false, msg: '无法添加项目' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', matchgroup })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }

    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：{"groupname": "少年组","minBirthDay": "2008-09-09","maxBirthDay": "2024-09-09", "matchId":1}', error: error.message })
    }
});
//6.1 获取赛事组别:matchgroup
app.get('/competition/matchgroup', authenticateToken, async (req, res) => {
    try {
        let matchgroups = await MatchGroup.findAll({ where: { matchId: req.user.matchId } })
        if (!matchgroups) {
            return res.status(501).json({ success: false, msg: '无法获取赛事组别' })
        } else {
            return res.status(200).json({ success: true, msg: '成功', matchgroups })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//6.2 删除赛事组别:matchgroup
app.delete('/competition/matchgroup/:matchGroupId', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            let num = await MatchGroup.destroy({ where: { matchId: req.user.matchId, id: req.params.matchGroupId } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除赛事组别' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确 /competition/matchgroup/:matchGroupId', error: error.message })
    }
});
//6.3 修改赛事组别:matchgroup
app.put('/competition/matchgroup', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == "管理员") {// 如果是管理员，则可以添加项目
            const { id, groupname, minBirthDay, maxBirthDay } = req.body
            let matchgroup = await MatchGroup.findByPk(id)
            matchgroup.groupname = groupname
            matchgroup.minBirthDay = minBirthDay
            matchgroup.maxBirthDay = maxBirthDay
            matchgroup = await matchgroup.save()
            if (!matchgroup) {
                return res.status(501).json({ success: false, msg: '无法添加项目' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', matchgroup })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }

    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：{"groupname": "少年组","minBirthDay": "2008-09-09","maxBirthDay": "2024-09-09", "matchId":1}', error: error.message })
    }
});
//6.4 获取某一赛事组别:matchgroup
app.get('/competition/matchgroup/:id', authenticateToken, async (req, res) => {
    try {
        let matchgroup = await MatchGroup.findOne({ where: { matchId: req.user.matchId, id: req.params.id } })
        if (!matchgroup) {
            return res.status(501).json({ success: false, msg: '无法获取赛事组别' })
        } else {
            return res.status(200).json({ success: true, msg: '成功', matchgroup })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});


//==========参赛团队管理==========
//7. 添加参赛团队
app.post('/competition/teamgroup/add', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == '普通用户') {
            // 如果当前比赛中已经存在一个团队，则不允许新创建。
            const existTeamGroup = TeamGroup.findOne({ where: { matchId: req.user.matchId, userId: req.user.userId } })
            if (existTeamGroup) {
                return res.status(501).json({ success: false, msg: '本用户在本次比赛中已经有团队存在了，请在已有团队中修改团队信息，获先删除该团队信息后再添加' })
            }
            const { teamName, teamAbbreviation, englishName, nation, province,
                city, address, teamLeader, phone, email, slogan, image } = req.body

            let teamGroup = TeamGroup.build({
                teamName, teamAbbreviation, englishName, nation, province, city, address,
                teamLeader, phone, email, slogan, image, matchId: req.user.matchId, userId: req.user.userId
            })
            teamGroup = await teamGroup.save()
            if (!teamGroup) {
                return res.status(501).json({ success: false, msg: '无法添加项目' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamGroup })
            }
        } else {
            return res.status(502).json({ success: false, msg: '缺少权限' })
        }


    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：', error: error.message })
    }
});

//7.1 获取参赛团队:teamgroup
app.get('/competition/teamgroup', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let teamGroups = await TeamGroup.findAll({ where: { matchId: req.user.matchId } })
            if (!teamGroups) {
                return res.status(501).json({ success: false, msg: '无法获取赛事组别' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamGroups })
            }
        } else {
            let teamGroup = await TeamGroup.findOne({ where: { matchId: req.user.matchId, userId: req.user.userId } })
            if (!teamGroup) {
                return res.status(501).json({ success: false, msg: '无法获取赛事组别' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamGroup })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//7.2 删除参赛团队:teamgroup
app.delete('/competition/teamgroup/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "普通用户") {// 如果是管理员，则可以添加项目
            let num = await TeamGroup.destroy({ where: { matchId: req.user.matchId, id: req.params.id, userId: req.user.userId } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛团队' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        } else if (req.user.role == "管理员") {
            let num = await TeamGroup.destroy({ where: { matchId: req.user.matchId, id: req.params.id } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛团队' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确 /competition/teamgroup/:id', error: error.message })
    }
});

//7.3 修改赛事组别:teamgroup
app.put('/competition/teamgroup', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == "普通用户") {// 如果是管理员，则可以添加项目
            const { id, teamName, teamAbbreviation, englishName, nation, province,
                city, address, teamLeader, phone, email, slogan, image } = req.body

            let teamGroup = await TeamGroup.findByPk(id)
            console.log(teamGroup)
            if (teamGroup.userId != req.user.userId || teamGroup.matchId != req.user.matchId) {
                return res.status(406).json({ success: false, msg: '你不能修改不是自己的团队' })
            }
            teamGroup.teamName = teamName
            teamGroup.teamAbbreviation = teamAbbreviation
            teamGroup.englishName = englishName
            teamGroup.nation = nation
            teamGroup.province = province
            teamGroup.province = province
            teamGroup.city = city
            teamGroup.address = address
            teamGroup.teamLeader = teamLeader
            teamGroup.phone = phone
            teamGroup.email = email
            teamGroup.slogan = slogan
            teamGroup.image = image
            teamGroup = await teamGroup.save()
            if (!teamGroup) {
                return res.status(501).json({ success: false, msg: '无法修改团队' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamGroup })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }

    }
    catch (error) {
        res.status(500).json({
            success: false, msg: '参数不正确，举例：{"id":1,' +
                '"teamName": "队伍1",' +
                '"teamAbbreviation": "队伍1",' +
                '"englishName": "duiwu1",' +
                '"nation": "中国",' +
                '"province": "湖南",' +
                '"city": "长沙",' +
                '"address": "青园路168号",' +
                '"teamLeader": "张队",' +
                ' "phone": "15116388122",' +
                '"email": "zhang@163.com",' +
                '"slogan": "win win win",' +
                '"image": "static/upload/images/file-1728058933057.jpg"' +
                '}', error: error.message
        })
    }
});


//7.4 获取某一团队:teamgroup
app.get('/competition/teamgroup/:id', authenticateToken, async (req, res) => {
    try {
        if(req.user.role =='管理员'){
            let teamgroup = await TeamGroup.findOne({ where: { matchId: req.user.matchId, id: req.params.id } })
            if (!teamgroup) {
                return res.status(501).json({ success: false, msg: '无法获取参赛团队' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamgroup })
            }
        }else{
            let teamgroup = await TeamGroup.findOne({ where: { matchId: req.user.matchId, id: req.params.id,userId:req.user.userId } })
            if (!teamgroup) {
                return res.status(501).json({ success: false, msg: '无法获取赛事组别' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamgroup })
            }
        }
       
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//======团队成员管理=====
//8 添加团队成员
app.post('/competition/staff/add', authenticateToken, async (req, res) => {
    try {
        console.log(req.user)
        if (req.user.role == '普通用户') {
            // 如果当前比赛中已经存在一个团队，则不允许新创建。
            const existTeamGroup = TeamGroup.findOne({ where: { matchId: req.user.matchId, userId: req.user.userId } })
            if (!existTeamGroup) {
                return res.status(501).json({ success: false, msg: '请先创建团队再添加团队成员' })
            }
            const { role, idcard, urealName, sex, birthday,
                phone, email, image, teamGroupId, matchesGroupId } = req.body

            let staff = Staff.build({
                role, idcard, urealName, sex, birthday,
                phone, email, image, teamGroupId, matchesGroupId, userId: req.user.userId,matchId:req.user.matchId
            })
            staff = await staff.save()
            if (!staff) {
                return res.status(501).json({ success: false, msg: '无法添加团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staff })
            }
        } else {
            return res.status(502).json({ success: false, msg: '缺少权限' })
        }


    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：', error: error.message })
    }
});


//8.1.查询指定团队的所有成员
app.get('/competition/staff/:teamGroupId', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let staffs = await Staff.findAll({ where: { teamGroupId: req.params.teamGroupId } })
            if (!staffs) {
                return res.status(501).json({ success: false, msg: '无法获取团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staffs })
            }
        } else {
            let staffs = await Staff.findAll({ where: { teamGroupId: req.params.teamGroupId, userId: req.user.userId } })
            if (!staffs) {
                return res.status(501).json({ success: false, msg: '无法获取团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staffs })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//8.2 删除参赛团队成员:staff
app.delete('/competition/staff/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "普通用户") {// 如果是管理员，则可以添加项目
            let num = await Staff.destroy({ where: {id: req.params.id, userId: req.user.userId } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        } else if (req.user.role == "管理员") {
            let num = await TeamGroup.destroy({ where: { id: req.params.id } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛团队' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确 /competition/staff/:id', error: error.message })
    }
});

//8.3 修改参赛团队成员:staff
app.put('/competition/staff', authenticateToken, async (req, res) => {

    try {
        console.log(req.user)
        if (req.user.role == "普通用户") {// 如果是管理员，则可以添加项目
            const { id, role, idcard, urealName, sex, birthday,
                phone, email, image,  matchesGroupId } = req.body

            let staff = await Staff.findByPk(id)
            console.log(staff)
            if (staff.userId != req.user.userId) {
                return res.status(406).json({ success: false, msg: '你不能修改不是自己的团队成员' })
            }
            staff.role = role
            staff.idcard = idcard
            staff.urealName = urealName
            staff.sex = sex
            staff.birthday = birthday
            staff.phone = phone
            staff.email = email
            staff.image = image
            staff.matchesGroupId = matchesGroupId
            staff = await staff.save()
            if (!staff) {
                return res.status(501).json({ success: false, msg: '无法修改团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staff })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限' })
        }

    }
    catch (error) {
        res.status(500).json({
            success: false, msg: '参数不正确，举例：{"id":1,' +
                '"teamName": "队伍1",' +
                '"teamAbbreviation": "队伍1",' +
                '"englishName": "duiwu1",' +
                '"nation": "中国",' +
                '"province": "湖南",' +
                '"city": "长沙",' +
                '"address": "青园路168号",' +
                '"teamLeader": "张队",' +
                ' "phone": "15116388122",' +
                '"email": "zhang@163.com",' +
                '"slogan": "win win win",' +
                '"image": "static/upload/images/file-1728058933057.jpg"' +
                '}', error: error.message
        })
    }
});

//8.4 获取某一团队成员:staff
app.get('/competition/staff/byStaffId/:id', authenticateToken, async (req, res) => {
    try {
        if(req.user.role =='管理员'){
            let staff = await Staff.findOne({ where: {id: req.params.id } })
            if (!staff) {
                return res.status(501).json({ success: false, msg: '无法获取参赛团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staff })
            }
        }else{
            let staff = await Staff.findOne({ where: {  id: req.params.id,userId:req.user.userId } })
            if (!staff) {
                return res.status(501).json({ success: false, msg: '无法获取参赛团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staff })
            }
        }
       
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});
//8.5 通过姓名查询人员信息:staff
app.post('/competition/staff/getByusername', authenticateToken, async (req, res) => {
    try {
        if(req.user.role =='管理员'){
            let staffs = await Staff.findAll({ where: {matchId: req.user.matchId, urealName:{
                [Sequelize.Op.like]: `%${req.body.username}%`
            } } })
            if (!staffs) {
                return res.status(501).json({ success: false, msg: '无法获取参赛团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staffs })
            }
        }else{
            let staffs = await Staff.findAll({ where: {matchId: req.user.matchId, userId:req.user.userId,urealName:{
                [Sequelize.Op.like]: `%${req.body.username}%`
            } } })
            
            if (!staffs) {
                return res.status(501).json({ success: false, msg: '无法获取参赛团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', staffs })
            }
        }
       
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});


//======赛项队伍管理=====
//9 添加赛项队伍【就是报名信息,编号即是赛项队伍编号】
app.post('/competition/projectteam/add', authenticateToken, async (req, res) => {
    try {
        console.log(req.user)
        if (req.user.role == '普通用户') {
            const { projectId, teamGroupId, difficultDeclare, contentDecalare,
                } = req.body

            let projectTeam = ProjectTeam.build({
                projectId, teamGroupId, difficultDeclare, contentDecalare,
                userId:req.user.userId,matchId:req.user.ma
            })
            projectTeam = await projectTeam.save()
            if (!projectTeam) {
                return res.status(501).json({ success: false, msg: '无法添加赛项队伍报名信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeam })
            }
        } else {
            return res.status(502).json({ success: false, msg: '缺少权限' })
        }


    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：', error: error.message })
    }
});


//9.1.查询指定团队的所有赛项队伍
app.get('/competition/projectteam/getByTeamGroup/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let projectTeams = await ProjectTeam.findAll({ where: { teamGroupId: req.params.id } })
            if (!projectTeams) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeams })
            }
        } else {
            let projectTeams = await ProjectTeam.findAll({ where: { teamGroupId: req.params.id, userId: req.user.userId } })
            if (!projectTeams) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeams })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//9.2.查询指定赛项的所有赛项队伍
app.get('/competition/projectteam/getByProject/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let projectTeams = await ProjectTeam.findAll({ where: { projectId: req.params.id } })
            if (!projectTeams) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeams })
            }
        } else {
            let projectTeams = await ProjectTeam.findAll({ where: { projectId: req.params.id, userId: req.user.userId } })
            if (!projectTeams) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeams })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});
//9.3.查询指定比赛的所有赛项队伍
app.get('/competition/projectteam/getByMatch/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let projectTeams = await ProjectTeam.findAll({ where: { matchId: req.params.id } })
            if (!projectTeams) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeams })
            }
        } else {
            let projectTeams = await ProjectTeam.findAll({ where: { matchId: req.params.id, userId: req.user.userId } })
            if (!projectTeams) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeams })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//9.4 删除赛项队伍:projectteam
app.delete('/competition/projectteam/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "普通用户") {// 如果是管理员，则可以添加项目
            let num = await ProjectTeam.destroy({ where: {id: req.params.id, userId: req.user.userId } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        } else if (req.user.role == "管理员") {
            let num = await ProjectTeam.destroy({ where: { id: req.params.id } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛团队' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确 /competition/projectteam/:id', error: error.message })
    }
});



// 9.5 修改赛项队伍：projectteam
app.put('/competition/projectteam', authenticateToken, async (req, res) => {

    try {
        console.log(req.user.role)
        if (req.user.role == '普通用户') {// 如果是管理员，则可以添加项目
            const { id, difficultDeclare, contentDecalare,projectTeamScore } = req.body

            let projectTeam = await ProjectTeam.findByPk(id)
            console.log(projectTeam)
            if (projectTeam.userId != req.user.userId) {
                return res.status(406).json({ success: false, msg: '你不能修改不是自己的项目队伍' })
            }
            projectTeam.difficultDeclare = difficultDeclare
            projectTeam.contentDecalare = contentDecalare
            projectTeam.projectTeamScore = projectTeamScore
            projectTeam = await projectTeam.save()
            if (!projectTeam) {
                return res.status(501).json({ success: false, msg: '无法修改团队成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeam })
            }

        } else {
            return res.status(501).json({ success: false, msg: '缺少权限1' })
        }

    }
    catch (error) {
        res.status(500).json({
            success: false, msg: '参数不正确，举例：{"id":1,' +
                '"teamName": "队伍1",' +
                '"teamAbbreviation": "队伍1",' +
                '"englishName": "duiwu1",' +
                '"nation": "中国",' +
                '"province": "湖南",' +
                '"city": "长沙",' +
                '"address": "青园路168号",' +
                '"teamLeader": "张队",' +
                ' "phone": "15116388122",' +
                '"email": "zhang@163.com",' +
                '"slogan": "win win win",' +
                '"image": "static/upload/images/file-1728058933057.jpg"' +
                '}', error: error.message
        })
    }
});

//9.6 获取某一赛项队伍:projectteam
app.get('/competition/projectteam/byProjectTeamId/:id', authenticateToken, async (req, res) => {
    try {
        if(req.user.role =='管理员'){
            let projectTeam = await ProjectTeam.findOne({ where: {id: req.params.id } })
            if (!projectTeam) {
                return res.status(501).json({ success: false, msg: '无法获取参赛队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeam })
            }
        }else{
            let projectTeam = await ProjectTeam.findOne({ where: {  id: req.params.id,userId:req.user.userId } })
            if (!projectTeam) {
                return res.status(501).json({ success: false, msg: '无法获取参赛队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', projectTeam })
            }
        }
       
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//======赛项队伍人员管理=====
//10 添加赛项队伍人员【赛项队伍 包含的人员添加，表示对应人员属于某一赛项队伍】
app.post('/competition/teamstaff/add', authenticateToken, async (req, res) => {
    try {
        console.log(req.user)
        if (req.user.role == '普通用户') {
            const { teamId, staffId } = req.body

            let teamStaff = TeamStaff.build({
                teamId,
                 staffId,
                userId:req.user.userId
            })
            teamStaff = await teamStaff.save()
            if (!teamStaff) {
                return res.status(501).json({ success: false, msg: '无法添加赛项队伍人员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamStaff })
            }
        } else {
            return res.status(502).json({ success: false, msg: '缺少权限' })
        }


    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例：', error: error.message })
    }
});

//10.1 查询指定赛项队伍所有人员
app.get('/competition/teamstaff/getStaffByTeam/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let teamStaffs = await TeamStaff.findAll({ where: { teamId: req.params.id } })
            console.log("打印队伍成员信息"+teamStaffs)
            if (!teamStaffs) {
                return res.status(501).json({ success: false, msg: '无法获取指定队伍成员信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamStaffs })
            }
        } else {
            let teamStaffs = await TeamStaff.findAll({ where: { teamId: req.params.id, userId: req.user.userId } })
            console.log("打印队伍成员信息"+JSON.stringify(teamStaffs))
            if (!teamStaffs) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamStaffs })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});

//10.2.查询指定人员的所有赛项队伍
app.get('/competition/teamstaff/getTeamByStaff/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == '管理员') {
            let teamStaffs = await TeamStaff.findAll({ where: { staffId: req.params.id } })
            console.log("打印队伍成员信息"+teamStaffs)
            if (!teamStaffs) {
                return res.status(501).json({ success: false, msg: '无法获取指定队伍成员信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamStaffs })
            }
        } else {
            let teamStaffs = await TeamStaff.findAll({ where: { staffId: req.params.id, userId: req.user.userId } })
            console.log("打印队伍成员信息"+JSON.stringify(teamStaffs))
            if (!teamStaffs) {
                return res.status(501).json({ success: false, msg: '无法获取团队的所有队伍信息' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', teamStaffs })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确', error: error.message })
    }
});
//10.3 删除赛项队伍:teamstaff
app.delete('/competition/teamstaff/:id', authenticateToken, async (req, res) => {
    try {
        if (req.user.role == "普通用户") {// 如果是管理员，则可以添加项目
            let num = await TeamStaff.destroy({ where: {id: req.params.id, userId: req.user.userId } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛队伍成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        } else if (req.user.role == "管理员") {
            let num = await TeamStaff.destroy({ where: { id: req.params.id } })
            if (!num) {
                return res.status(501).json({ success: false, msg: '无法删除参赛队伍成员' })
            } else {
                return res.status(200).json({ success: true, msg: '成功', num })
            }
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确 /competition/staff/:id', error: error.message })
    }
});



//==================== 省份和城市数据=================

//11.获取所有省份数据
app.get('/competition/province', async (req, res) => {
    try {

        let provices = await Province.findAll()
        if (!provices) {
            return res.status(501).json({ success: false, msg: '无法获取省份数据' })
        } else {
            return res.status(200).json({ success: true, msg: '成功', provices })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例', error: error.message })
    }
});
//12.获取指定省份城市数据
app.get('/competition/city/:privinceId', async (req, res) => {
    try {

        let cities = await City.findAll({where:{
            provinceid:req.params.privinceId
        }})
        if (!cities) {
            return res.status(501).json({ success: false, msg: '无法获取城市数据' })
        } else {
            return res.status(200).json({ success: true, msg: '成功', cities })
        }
    }
    catch (error) {
        res.status(500).json({ success: false, msg: '参数不正确，举例=', error: error.message })
    }
});






// 示例受保护的路由
app.get('/addMatches', authenticateToken, (req, res) => {
    res.json({ message: 'You have accessed a protected route', user: req.user });
});


// 启动服务器

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
